package com.lipi.mall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lipi.common.constant.ProductConstant;
import com.lipi.common.utils.PageUtils;
import com.lipi.common.utils.Query;
import com.lipi.mall.product.dao.AttrAttrgroupRelationDao;
import com.lipi.mall.product.dao.AttrDao;
import com.lipi.mall.product.dao.AttrGroupDao;
import com.lipi.mall.product.dao.CategoryDao;
import com.lipi.mall.product.entity.AttrAttrgroupRelationEntity;
import com.lipi.mall.product.entity.AttrEntity;
import com.lipi.mall.product.entity.AttrGroupEntity;
import com.lipi.mall.product.entity.CategoryEntity;
import com.lipi.mall.product.service.AttrService;
import com.lipi.mall.product.service.CategoryService;
import com.lipi.mall.product.vo.AttrGroupRelationVO;
import com.lipi.mall.product.vo.AttrRespVO;
import com.lipi.mall.product.vo.AttrVO;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.swing.*;
import java.util.*;
import java.util.stream.Collectors;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    private AttrAttrgroupRelationDao attrAttrgroupRelationDao;

    @Autowired
    private CategoryDao categoryDao;

    @Autowired
    private AttrGroupDao attrGroupDao;

    @Autowired
    private CategoryService categoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveAttr(AttrVO attr) {
        //保存attr信息
        AttrEntity attrGroupEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrGroupEntity);
        this.save(attrGroupEntity);
        //如果是基本属性,保存关联关系
        if (attr.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            attrAttrgroupRelationEntity.setAttrGroupId(attr.getAttrGroupId());
            attrAttrgroupRelationEntity.setAttrId(attrGroupEntity.getAttrId());

            attrAttrgroupRelationDao.insert(attrAttrgroupRelationEntity);
        }


    }

    @Override
    public PageUtils queryPage(Map<String, Object> params, Long categoryId, String attrType) {
        String key = (String) params.get("key");
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper();
        //鉴别操作类型
        wrapper.eq("attr_type", "base".equalsIgnoreCase(attrType) ? ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() : ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode());

        //根据id或name模糊查询
        if (StringUtils.isNotEmpty(key)) {
            wrapper.eq("attr_id", key).or().like("attr_name", key);
        }
        //根据catelog查询
        IPage<AttrEntity> page;
        if (categoryId == null || categoryId == 0) {
            page = this.page(new Query<AttrEntity>().getPage(params), wrapper);
        } else {
            wrapper.eq("catelog_id", categoryId);
            page = this.page(new Query<AttrEntity>().getPage(params), wrapper);
        }
        List<AttrEntity> records = page.getRecords();
        List<AttrRespVO> attrRespVoList = records.stream()
                .map((attrEntity) -> {
                    AttrRespVO attrRespVO = new AttrRespVO();
                    BeanUtils.copyProperties(attrEntity, attrRespVO);

                    //封装catelog
                    Long catelogId = attrEntity.getCatelogId();
                    CategoryEntity categoryEntity = categoryDao.selectById(catelogId);

                    attrRespVO.setCatelogName(categoryEntity.getName());
                    //封装attr_group
                    //1、从attr_attrGroup_relation查询group_id
                    AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = attrAttrgroupRelationDao.selectOne(
                            new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));


                    //2、从attrGroup查询group_name
                    //如果是销售属性，不存在分组关联
                    if (attrType.equalsIgnoreCase("base")) {
                        if (!(attrAttrgroupRelationEntity == null || attrAttrgroupRelationEntity.getAttrGroupId() == null)) {
                            AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrAttrgroupRelationEntity.getAttrGroupId());
                            if (attrGroupEntity != null) {
                                attrRespVO.setGroupName(attrGroupEntity.getAttrGroupName());
                            }

                        }
                    }
                    return attrRespVO;
                })
                .collect(Collectors.toList());
        PageUtils pageUtils = new PageUtils(page);
        //修改结果集，分页参数不动
        pageUtils.setList(attrRespVoList);
        return pageUtils;
    }

    @Cacheable(value = "attr", key = "'attrInfo'+#root.args[0]")
    @Override
    public AttrRespVO getAttrInfo(Long attrId) {
        AttrEntity attrEntity = this.getById(attrId);

        AttrRespVO attrRespVO = new AttrRespVO();
        BeanUtils.copyProperties(attrEntity, attrRespVO);

        //封装catelogPath完整路径和categoryName
        attrRespVO.setCatelogPath(categoryService.getCategoryPath(attrEntity.getCatelogId()));
        attrRespVO.setCatelogName(categoryService.getById(attrEntity.getCatelogId()).getName());

        //如果是基本信息，需要封装groupId和groupName
        if (attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = attrAttrgroupRelationDao.selectOne(
                    new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));

            if (!(attrAttrgroupRelationEntity == null || attrAttrgroupRelationEntity.getAttrGroupId() == null)) {
                attrRespVO.setAttrGroupId(attrAttrgroupRelationEntity.getAttrGroupId());

                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrAttrgroupRelationEntity.getAttrGroupId());
                attrRespVO.setGroupName(attrGroupEntity.getAttrGroupName());
            }
        }


        return attrRespVO;
    }

    @Override
    public void updateByAttr(AttrVO attrVO) {
        //1、修改基本数据
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attrVO, attrEntity);
        this.updateById(attrEntity);
        //2、若是基本属性，修改冗余的关联数据
        //2.1 修改attr_attrGroup_relation
        //修改前先判断是否存在分组关联
        //存在关联，为修改操作
        if (attrVO.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            Integer count = attrAttrgroupRelationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrVO.getAttrId()));

            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            attrAttrgroupRelationEntity.setAttrGroupId(attrVO.getAttrGroupId());
            attrAttrgroupRelationEntity.setAttrId(attrVO.getAttrId());
            if (count > 0) {
                attrAttrgroupRelationDao.update(attrAttrgroupRelationEntity
                        , new UpdateWrapper<AttrAttrgroupRelationEntity>()
                                .eq("attr_id", attrVO.getAttrId()));
            } else {
                //新增操作
                attrAttrgroupRelationDao.insert(attrAttrgroupRelationEntity);
            }
        }
    }

    @Override
    /**
     * 根据分组ID查找所有的基本属性
     * "data": [
     *     {
     *       "attrId": 4,
     *       "attrName": "aad",
     *       "searchType": 1,
     *       "valueType": 1,
     *       "icon": "qq",
     *       "valueSelect": "v;q;w",
     *       "attrType": 1,
     *       "enable": 1,
     *       "catelogId": 225,
     *       "showDesc": 1
     *     }
     *   ]
     */
    public List<AttrEntity> getRelationAttr(Long attrgroupId) {
        List<AttrEntity> entities = new ArrayList<>();
        List<AttrAttrgroupRelationEntity> relationEntityList = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrgroupId));

        List collect = relationEntityList.stream().map(
                (attr) -> {
                    return attr.getAttrId();
                }
        ).collect(Collectors.toList());

        if (collect != null && collect.size() != 0) {

            Collection<AttrEntity> attrEntitys = this.listByIds(collect);
            List<AttrEntity> res = (List<AttrEntity>) attrEntitys;
            return res;
        } else {
            return new ArrayList<AttrEntity>();
        }

    }

    @Override
    public void deleteRelation(AttrGroupRelationVO[] vos) {
        List<AttrAttrgroupRelationEntity> collect = Arrays.asList(vos).stream().map(
                (item) -> {
                    AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
                    BeanUtils.copyProperties(item, attrAttrgroupRelationEntity);
                    return attrAttrgroupRelationEntity;
                }
        ).collect(Collectors.toList());

        attrAttrgroupRelationDao.deleteBatchRelation(collect);
    }

    /**
     * 获取当前分组没有关联的所有属性(所属分类没有被使用的分组)
     *
     * @param params
     * @param attrgroupId
     * @return
     */
    @Override
    public PageUtils getNoRelationAttr(Map<String, Object> params, Long attrgroupId) {
        // 1：当前分组只能关联自己所属的分类里面的属性
        // 1.1：查询当前分组所属分类
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectOne(new QueryWrapper<AttrGroupEntity>().eq("attr_group_id", attrgroupId));
        Long catelogId = attrGroupEntity.getCatelogId();

        // 2：当前分组只能关联别的分组没有引用的属性
        // 2.1：当前分类下的其他分组
        List<AttrGroupEntity> otherGroupList = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId));
        // 2.2：查询其它分组关联的属性
        List<Object> collect = otherGroupList.stream().map((item) -> {
            return item.getAttrGroupId();
        }).collect(Collectors.toList());

        List<AttrAttrgroupRelationEntity> otherRelation = attrAttrgroupRelationDao.selectList(
                new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", collect));

        List<Long> otherAttrIdList = otherRelation.stream()
                .map((item) -> {
                    return item.getAttrId();
                })
                .collect(Collectors.toList());
        // 2.3：过滤掉2.2的属性
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>().eq("catelog_id", catelogId).eq("attr_type", ProductConstant.AttrEnum.ATTR_TYPE_BASE);
        if (otherAttrIdList != null && otherAttrIdList.size() > 0) {
            queryWrapper.notIn("attr_id", otherAttrIdList);
        }
        if (StringUtils.isNotEmpty((String) params.get("key"))) {
            queryWrapper.eq("attr_id", (String) params.get("key")).or().like("attr_name", (String) params.get("key"));
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), queryWrapper);

        return new PageUtils(page);
    }

    @Override
    public List<Long> selectSearchAttrs(List<Long> attrIds) {

        List<Long> searchableAttrs = this.baseMapper.selectSearchAttrIds(attrIds);

        return searchableAttrs;
    }
}